<template>
  <DetailsFormBox :title="page.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '仅保存',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, false)
      },
    },
    {
      title: '保存并确认',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, true)
      },
    },
    {
      title: '审核通过',
      icon: '',
      type: 'success',
      hidden: route.query.type !== '4',
      click: (form: any) => {
        setState(form, 3, '审核成功')
      },
    },
    {
      title: '审核拒绝',
      icon: '',
      type: 'danger',
      hidden: route.query.type !== '4',
      click: (form: any) => {
        proxy.$messageInputBox('请填写拒绝原因！', (value: string) => {
          setState(form, 2, '拒绝成功', value)
        });
      },
    },
  ]" :formInfo="[
    {
      label: '创建人员',
      value: 'createorName',
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
    {
      label: '审核人员',
      value: 'auditorName',
    },
    {
      label: '审核时间',
      value: 'auditTime',
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <div class="p-12">
        <OrderInfo :data="data.productOrder" :produceTaskBillNo="route.query.produceTaskBillNo" />
        <CellBox title="基本信息" isTop>
          <FlexBox>
            <ElFormItemBox label="核价单号" prop="goodsPriceAdjustmentNumber">
              <ElInputBox :data="form" dataName="goodsPriceAdjustmentNumber" placeholder="系统自动生成" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="单据状态" prop="goodsPriceAdjustmentState">
              <ElSelectBox :data="form" dataName="goodsPriceAdjustmentState" placeholder="系统自动生成" disabled
                :options="options.state" />
            </ElFormItemBox>
            <ElFormItemBox label="供应商" prop="supplierCode" isRules>
              <ElSelectBox :data="form" dataName="supplierCode" :options="options.supplier" :disabled="!isEdit"
                @changeBtn="(value: string) => {
                  form.detailList = []
                  getGoods(value)
                }" />
            </ElFormItemBox>
            <ElFormItemBox label="生效日期" prop="startTime" isRules>
              <ElDayBox :data="form" dataName="startTime" :disabled="!isEdit" />
            </ElFormItemBox>
            <ElFormItemBox label="核价备注" prop="remark" class="wAuto">
              <ElInputBox :data="form" dataName="remark" type="textarea" :disabled="!isEdit" />
            </ElFormItemBox>
            <ElFormItemBox label="作废原因" prop="disableReason" class="wAuto" v-if="form.goodsPriceAdjustmentState === 4">
              <ElInputBox :data="form" dataName="disableReason" type="textarea" :disabled="!isEdit" />
            </ElFormItemBox>
            <ElFormItemBox label="拒绝原因" prop="rejectReason" class="wAuto" v-if="form.goodsPriceAdjustmentState === 2">
              <ElInputBox :data="form" dataName="rejectReason" type="textarea" :disabled="!isEdit" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="单据明细" isTop>
          <TableBoxMx :data="{
            disabled: !isEdit,
            tbody: form.detailList,
            thead: [
              {
                label: '物料编号',
                prop: 'goodsCode',
                width: 120,
                align: 'center',
              },
              {
                label: '物料名称',
                prop: 'goodsName',
                width: 220,
                align: 'left',
              },
              {
                label: '物料类型',
                prop: 'goodsType',
                width: 120,
                align: 'center',
              },
              {
                label: '原单价',
                prop: 'goodsPriceLast',
                width: 120,
                align: 'center',
              },
              {
                label: '原核准日期',
                prop: 'createTime',
                width: 120,
                align: 'center',
              },
              {
                label: '税率',
                prop: 'taxRate',
                width: 120,
                align: 'center',
                formType: 'number',
                formProp: 'detailList',//必填
                changeBtn: (value: any, row: any) => {
                  console.log(row);
                  proxy.$setTaxRate(row, {
                    taxRate: 'taxRate', // 税率
                    taxExcludedUnitPrice: 'goodsPriceCurrentBeforeTax', // 未税单价
                    taxIncludedUnitPrice: 'goodsPriceCurrent', // 含税单价
                  })
                }
              },
              {
                label: '含税单价',
                prop: 'goodsPriceCurrent',
                width: 120,
                align: 'center',
                formType: 'number',
                formProp: 'detailList',//必填
                changeBtn: (value: any, row: any) => {
                  proxy.$setTaxInclusiveUnitPrice(row, {
                    taxRate: 'taxRate', // 税率
                    taxExcludedUnitPrice: 'goodsPriceCurrentBeforeTax', // 未税单价
                    taxIncludedUnitPrice: 'goodsPriceCurrent', // 含税单价
                  })
                }
              },
              {
                label: '未税单价',
                prop: 'goodsPriceCurrentBeforeTax',
                width: 120,
                align: 'center',
                formType: 'number',
                formProp: 'detailList',//必填
                changeBtn: (value: any, row: any) => {
                  proxy.$setTaxExcludedUnitPrice(row, {
                    taxRate: 'taxRate', // 税率
                    taxExcludedUnitPrice: 'goodsPriceCurrentBeforeTax', // 未税单价
                    taxIncludedUnitPrice: 'goodsPriceCurrent', // 含税单价
                  })
                }
              },
              {
                label: '备注',
                prop: 'remark',
                width: null,
                align: 'left',
                formType: 'text',
              },
            ],
            operation: [
              {
                label: '删除',
                icon: 'Delete',
              }
            ],
            addSelect: addSelect
          }" @searchBtn="searchSelectBtn" @selectBtn="selectMxBtn">
            <template #goodsName="{ row }">
              {{ goodsName(row) }}
            </template>
            <template #search="{ search }">
              <ElFormItemBox label="物料名称" prop="goodsName">
                <ElInputBox :data="search" dataName="goodsName" />
              </ElFormItemBox>
            </template>
          </TableBoxMx>
        </CellBox>
      </div>
    </template>
  </DetailsFormBox>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import { useListComponent } from '../pageTs'; // 引入逻辑
import page from '../page.ts'; // 引入逻辑
import '../pageCss.scss'; // 引入样式
const { dataInfo, options } = useListComponent();
const { proxy } = getCurrentInstance() as any;
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  mainPage: 1,
  form: {
    goodsPriceAdjustmentID: null, // 物料调价单主键ID
    goodsPriceAdjustmentCode: "", // 物料调价单编码
    goodsPriceAdjustmentNumber: "", // 物料调价单编号
    goodsPriceAdjustmentState: 0, // 物料调价单状态：0-待确认、1-待审核、2-已拒绝、3-已完成、4-已作废
    supplierCode: "", // 供应商编码
    supplierName: "", // 供应商名称（新增/修改忽略）
    startTime: "", // 生效时间
    remark: "", // 备注
    isEffective: 0, // 是否生效：0-未生效，1-已生效
    rejectReason: "", // 审核拒绝原因
    disableReason: "", // 作废原因
    auditTime: "", // 审核时间（新增/修改忽略）
    auditor: "", // 审核人（新增/修改忽略）
    auditorName: "", // 审核人名称（新增/修改忽略）
    createor: "", // 创建人员（新增/修改忽略）
    createorName: "", // 创建人员名称（新增/修改忽略）
    uploador: "", // 修改人员（新增/修改忽略）
    detailList: [
      // {
      //   goodsPriceAdjustmentDetailID: 0, // 物料调价明细主键ID
      //   goodsPriceAdjustmentDetailCode: "", // 物料调价明细编码
      //   goodsPriceAdjustmentCode: "", // 所属物料调价单编码
      //   supplierGoodsNumber: "", // 供应商料号
      //   goodsCode: "", // 物料编码
      //   goodsName: "", // 物料名称（新增/修改忽略）
      //   goodsTypeName: "", // 物料类型名称（新增/修改忽略）
      //   goodsUnitName: "", // 物料单位名称（新增/修改忽略）
      //   priceUnitName: "", // 计价单位名称（新增/修改忽略）
      //   goodsPriceLast: null, // 上次价格
      //   goodsPriceLastTime: "", // 上次核价时间
      //   goodsPriceCurrent: null, // 当前含税单价
      //   goodsPriceCurrentBeforeTax: null, // 当前未税单价
      //   taxRate: 0.13, // 税率（如：13%）
      //   remark: "", // 备注
      //   createor: "" // 创建人员（新增/修改忽略）
      // }
    ]
  },
});
const goodsName = (row: any) => {
  const _row: any = options.goods.find((el: any) => el.goodsCode === row.goodsCode)
  if (_row) {
    row.goodsType = _row.goodsType
  }
  return _row ? _row.goodsName : '--'
}
const searchSelectBtn = () => {
  addSelect.tbody = JSON.parse(JSON.stringify(options.goods))
    .filter((el: any) => !addSelect.search.goodsName || el.goodsName.includes(addSelect.search.goodsName))
}
const selectMxBtn = (arr: any) => {
  const _arr = arr.map((el: any) => ({
    goodsCode: el.goodsCode,
    goodsName: el.goodsName,
    goodsType: el.goodsType,
    goodsPriceLast: el.goodsPrice,
    createTime: el.goodsPriceAdjustmentTime,
    taxRate: 0.13,
    goodsPriceCurrentBeforeTax: null,
    goodsPriceCurrent: null,
    remark: "",
  }))
  data.form.detailList.push(..._arr)
}
const addSelect = reactive({
  rowKey: 'goodsCode',
  search: {
    goodsName: '',
  },
  thead: [
    {
      label: '物料编号',
      prop: 'goodsCode',
      align: 'center',
      width: 120,
    },
    {
      label: '物料名称',
      prop: 'goodsName',
      align: 'left',
      width: null,
    },
    {
      label: '物料类型',
      prop: 'goodsType',
      align: 'center',
      width: 120,
    },
    {
      label: '物料单位',
      prop: 'goodsUnit',
      align: 'center',
      width: 120,
    },
    {
      label: '计价单位',
      prop: 'priceUnit',
      align: 'center',
      width: 120,
    },
    {
      label: '原物料单价',
      prop: 'goodsPrice',
      align: 'center',
      width: 120,
    },
    {
      label: '原核价时间',
      prop: 'goodsPriceAdjustmentTime',
      align: 'center',
      width: 160,
    },
  ],
  tbody: [],
})
const isEdit = ref(true)

import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
//获取数据
const getForm = async () => {
  let _query: any = route.query
  setLoading()
  //获取工单信息
  //是否新建
  if (!!!_query.code) {
    data.loading = false
    return
  }
  proxy.$api.GoodsPriceAdjustment.GetGoodsPriceAdjustmentByCode({
    queryBy: 2,
    queryValue: _query.code,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = ['1', '2'].includes(_query.type) && res.goodsPriceAdjustmentState === 0
      data.form = {
        ...res,
        detailList: res.detailList.map((el: any) => ({
          ...el,
          taxRate: el.goodsPriceCurrent === el.goodsPriceCurrentBeforeTax ? 0 : el.taxRate,
        }))
      }
      getGoods(res.supplierCode)
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });
};
const saveBtn = (form: any, isConfirm: boolean = false) => {
  const _form: any = {
    goodsPriceAdjustmentID: form.goodsPriceAdjustmentID, // 物料调价单主键ID
    goodsPriceAdjustmentCode: form.goodsPriceAdjustmentCode, // 物料调价单编码
    goodsPriceAdjustmentNumber: form.goodsPriceAdjustmentNumber, // 物料调价单编号
    goodsPriceAdjustmentState: form.goodsPriceAdjustmentState, // 物料调价单状态：0-待确认、1-待审核、2-已拒绝、3-已完成、4-已作废
    supplierCode: form.supplierCode, // 供应商编码
    startTime: form.startTime, // 生效时间
    isEffective: form.isEffective || 0, // 是否生效：0-未生效，1-已生效
    rejectReason: form.rejectReason, // 审核拒绝原因
    disableReason: form.disableReason, // 作废原因
    remark: form.remark, // 备注
    detailList: form.detailList.map((el: any) => ({
      goodsPriceAdjustmentDetailID: el.goodsPriceAdjustmentDetailID, // 物料调价明细主键ID
      goodsPriceAdjustmentDetailCode: el.goodsPriceAdjustmentDetailCode, // 物料调价明细编码
      goodsPriceAdjustmentCode: form.goodsPriceAdjustmentCode, // 所属物料调价单编码
      supplierGoodsNumber: el.supplierGoodsNumber, // 供应商料号
      goodsCode: el.goodsCode, // 物料编码
      goodsPriceLast: el.goodsPriceLast, // 上次价格
      goodsPriceLastTime: el.goodsPriceLastTime, // 上次核价时间
      goodsPriceCurrent: el.goodsPriceCurrent, // 当前含税单价
      goodsPriceCurrentBeforeTax: el.goodsPriceCurrentBeforeTax, // 当前未税单价
      taxRate: el.taxRate || 0.13, // 税率（如：13%）
      remark: el.remark, // 备注
    }))
  }
  switch (route.query.type) {
    case '1'://新建
      proxy.$api.GoodsPriceAdjustment.AddGoodsPriceAdjustment({
        ..._form,
      })
        .then((res: any) => {
          if (isConfirm) {
            setState(res, 1, '保存成功')
          } else {
            _sun()
          }
        })
        .catch(() => { });
      break;
    case '2'://编辑
      proxy.$api.GoodsPriceAdjustment.UpdateGoodsPriceAdjustment(_form)
        .then((res: any) => {
          if (isConfirm) {
            setState(_form, 1, '保存成功')
          } else {
            _sun()
          }
        })
        .catch(() => { });
      break;

    default:
      break;
  }

  function _sun() {
    proxy.$message('保存成功')
    closeBtn()
  }
};

const closeBtn = () => {
  sendMsg('save', true);
  // getForm()
  window.close();
};
//更改状态
const setState = (row: any, state: number = 0, message: string = '操作成功', cancelReason?: string) => {
  proxy.$api.GoodsPriceAdjustment.UpdateGoodsPriceAdjustmentState({
    goodsPriceAdjustmentCode: row.goodsPriceAdjustmentCode, //核价单号
    reason: cancelReason, //作废/审核拒绝原因
    goodsPriceAdjustmentState: state, //核价单状态：0-待确认、1-待审核、2-已拒绝、3-已完成、4-已作废
    auditor: state === 3 ? proxy.$user.userName : '', //审核人
  })
    .then((res: any) => {
      proxy.$message(message);
      closeBtn()
    })
    .catch(() => { });
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};
const getGoods = (supplierCode: string) => {
  if (supplierCode) {
    proxy.$api.GoodsSpecification.GetGoodsSpecificationBySupplierCode({
      queryBy: 0,
      queryValue: supplierCode, //作废/审核拒绝原因
      onlyStocked: false, //是否仅查看核价过后的
      onlyPriceAdjustmented: false, //是否仅查看有库存的
    })
      .then((res: any) => {
        options.goods = res
      })
      .catch(() => { });
  } else {
    options.goods = []
  }
};

onMounted(() => {
  getForm();
});
</script>
